package com.itheima.reggie.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/order")
@RestController
public class OrderController {
    @Autowired(required = false)
    private OrderService orderService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        Orders order = orderService.submit(orders, userId);
        String id = order.getId()+"";
        BigDecimal amount = order.getAmount();

        session.setAttribute("id",id);
        session.setAttribute("amount",amount);
//        R<String> r = new R<>();
//        r.add("id",id);
//        r.add("amount",amount);

        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page<Orders>> userPage(Integer page, Integer pageSize) {
        Page<Orders> ordersList = orderService.userPage(page, pageSize);
        return R.success(ordersList);
    }

    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page, Integer pageSize,Long number,String beginTime,String endTime) {
        Page<Orders> ordersPage = orderService.page(page, pageSize,beginTime,endTime,number);
        return R.success(ordersPage);
    }

    @PostMapping("/updateStatus")
    @SuppressWarnings("unchecked")
    public R<String> updateStatus(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {

        ServletInputStream inputStream = request.getInputStream();

        XmlMapper xmlMapper = new XmlMapper();

        Map<String, String> map = xmlMapper.readValue(inputStream, Map.class);
//        String idStr = (String) session.getAttribute("id");
////        long id = Long.parseLong(idStr);

        orderService.updateStatus(map);

            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("return_code", "SUCCESS");
            resultMap.put("return_msg", "OK");


            String xmlData = xmlMapper.writeValueAsString(resultMap);
            response.setContentType("application/xml;charset=utf-8");
            response.getWriter().write(xmlData);

            return R.success("支付成功");

    }

}
